import {computed, watchEffect, readonly} from "vue";
import {createGlobalState, useLocalStorage} from "@vueuse/core";
import mxConst from "@/common/mxConst";
import mxConfig from "@/common/mxConfig";
import {getInfo, login, logout, logoutPhysical} from "@/api/login";
import {useCacheStore} from "@/hooks/useCacheStore";

export const useUserStore = createGlobalState(() => {
    // user data
    const token = useLocalStorage(mxConst.keyToken, '')
    const data = useLocalStorage(mxConst.keyUserInfo, {})
    const appConfig = useLocalStorage(mxConst.keyAppConfig, {})

    // computed
    const isLogin = computed(() => !!token.value)

    // hooks
    watchEffect(() => {
        mergeAppConfig()
    })

    // methods
    function mergeAppConfig() {
        const overrideConfig = appConfig.value
        const mergedConfig = uni.$uv.deepMerge(mxConfig, overrideConfig)
        Object.assign(mxConfig, mergedConfig)
        console.log('merge app config: to mx config', overrideConfig, mxConfig)
    }

    const Login = async function (userName, password) {
        const loginRes = await login(userName, password)
        token.value = loginRes.token
        const infoRes = await getInfo()
        data.value = infoRes.data
        appConfig.value = infoRes[mxConst.propAppConfig]

        // 每次重新登陆，主动清空所有缓存
        const {clearCache} = useCacheStore()
        clearCache()
    }

    const Logout = async function () {
        await logout()
        token.value = ''
        data.value = Object.create(null)
    }

    const LogoutPhysical = async function () {
        await logoutPhysical()
        token.value = ''
        data.value = Object.create(null)
    }

    return {
        token: readonly(token),
        currentUser: readonly(data),
        appConfig: readonly(appConfig),
        isLogin,
        Login,
        Logout,
        LogoutPhysical
    }
})
